<template>
  <div class="container">
    <div class="table">
      <a-alert 
        v-if="dataTable.tableTypeValue === 'graph'"
        message="双击文件名称进行修改" 
        style="margin-bottom: 20px;" 
        type="info" show-icon />

      <div class="toolbar">
        <div class="time_selection">
          <span 
            :class="{active: dataTable.timeValue === item.value}"
            v-for="(item,index) in TIMEOPTION" 
            :key="index"
            @click="changeTime(item.value)"
            >{{ item.label }}
          </span>
        </div>
        <div class="table_type">
          <a-icon 
            type="unordered-list" 
            @click="dataTable.tableTypeValue = 'list'"
            :style="{
              fontSize: '20px',
              cursor: 'pointer', 
              color: dataTable.tableTypeValue === 'list' ? '#409EFF' : ''
            }"/>
          <a-icon 
            type="table"
            @click="dataTable.tableTypeValue = 'graph'"
            :style="{
              fontSize: '20px', 
              marginLeft: '20px',
              cursor: 'pointer',
              color: dataTable.tableTypeValue === 'graph' ? '#409EFF' : ''
            }"/>
        </div>
      </div>

      <!-- 历史列表 -->
      <HistoryTable 
        v-show="dataTable.tableTypeValue === 'list'"
        :pageNo="dataTable.pageNo"
        :pageSize="dataTable.pageSize"
        :total="dataTable.total"
        @handlePageChange="handlePageChange"
        :isLoading="dataTable.isLoading"
        :tableData="dataTable.data">
        <template v-slot:btn="props">
          <el-button
            type="text"
            @click="goDetail(props.row)"
            size="small"
          >{{$t('page.view')}}</el-button>
          <el-button type="text"
            @click="downloadExl(props.row,0)"
            size="small"
            class="detial-btn">{{$t('page.download')}}</el-button>
          <el-button
            v-if="!isShowResultExcel"
            type="text"
            @click="downloadExl(props.row, originalTableNum)"
            size="small"
            class="detial-btn">{{$t('page.export')}}</el-button>
          <el-button type="text"
            v-if="!props.row.isEdit"
            @click="handleRdit(props.row)"
            size="small"
            class="detial-btn">{{$t('page.edit')}}</el-button>
          <el-button type="text"
            @click="handleRemove(props.row)"
            size="small"
            class="detial-btn">删除</el-button>
          <br/>
          <el-button type="text"
            v-if="props.row.isEdit"
            @click="handleSubmit(props.row)"
            size="small"
            class="detial-btn">{{$t('public.comfirmText')}}</el-button>
          <el-button type="text"
            v-if="props.row.isEdit"
            @click="handleRdit(props.row)"
            size="small"
            class="detial-btn">{{$t('page.cancel')}}</el-button>
          
        </template>
      </HistoryTable>

      <!-- 图形表格 -->
      <GraphTable
        :pageNo="dataTable.pageNo"
        :total="dataTable.total"
        :pageSize="dataTable.pageSize"
        @handlePageChange="handlePageChange"
        v-show="dataTable.tableTypeValue === 'graph'"
        :data="dataTable.data"
        v-loading="dataTable.isLoading"
      ></GraphTable>
    </div>
  </div>
</template>

<script>
import { fetchHistoryList, fetchUpdateName, deleteHistory } from "@/api/table";
import format from "date-format";
import { getStore } from '@/utils/common'
import { timeOption } from './constant'
import HistoryTable from '@/components/HistoryTable'
import GraphTable from "./graphTable";

export default {
  name: "",
  props: {
    // 下载原始表数字
    originalTableNum: {
      type: Number,
      default: 1,
      required: true
    },
    // 获取历史记录列表
    allListNum: {
      type: Number,
      default: 1,
      required: true
    },
    // 跳转详情页地址
    jumpUrl: {
      type: String,
      default: '/',
      required: true
    },
    // 是否显示下载结果 excel 
    isShowResultExcel: {
      type: Boolean,
      default: false
    },
    // 用于显示图形的字段
    parameter: {
      typw: Array,
      default: () => [
        {
          key: 'originalData_hl_merge',
          value: ''
        },
        {
          key: 'originalData_hl_merge_fitting',
          value: '拟合'
        }
      ]
    }
  },
  data() {
    return {
      lang: getStore('spr-lang') || 'zh',  
      dataTable: {
        pageNo: 1,
        pageSize: 12,
        total: 0,
        isLoading: false,
        data: [],
        timeValue: 0,
        tableTypeValue: 'graph', // list: 列表; graph: 图形
      },
    };
  },
  components: {
    HistoryTable,
    GraphTable
  },
  mounted() {
    this.getHistoryList();
  },
  provide() {
    return {
      handleChildRemove: (row) => this.handleRemove(row),
      handleChildSubmit: (row) => this.handleSubmit(row),
      handleDownExcel: (row) => this.downloadExl(row, 0),
      handleResultExcel: (row) => this.downloadExl(row, this.originalTableNum),
      handleToDetail: (row) => this.goDetail(row),
      isShowResultExcel: this.isShowResultExcel,
    }
  },
  methods: {
    // 删除历史记录
    handleRemove(row) {
      const _this = this
      this.$confirm({
        title: this.$t('page.deleteRecord'),
        content: this.$t('page.operatingTips'),
        cancelText: this.$t('public.cancel'),
        okText: this.$t('public.comfirmText'),
        onOk() {
          return new Promise((resolve, reject) => {
            try {
              deleteHistory(row.id).then(() => {
                _this.getHistoryList()
                _this.$message.success(_this.$t('public.deletionSucceeded'));
                resolve()
              })
            } catch(err) {
              reject()
              return
            }
          }).catch(() => console.log('Oops errors!'));
        },
        onCancel() {},
      });
    },

    // 确认修改
    async handleSubmit(row) {
      try {
        await fetchUpdateName({
          id: row.id,
          fileName: row.editValue
        })
        this.getHistoryList()
        this.$message.success(this.$t('page.modifyPrompt'));
      } catch(err) {
        return
      }
    },
    // 编辑功能
    handleRdit(row) {
      this.dataTable.data.forEach(item => {
        if(item.id === row.id) {
          item.isEdit = !item.isEdit
          item.editValue = item.fileName
        }
      })
    },
    //时间格式化
    formatterTime(t) {
      if (t) {
        const newTime = format("yyyy-MM-dd hh:mm:ss", new Date(t)).split(" ");
        let time = "";
        time += newTime[0] + "\xa0" + newTime[1];
        return time;
      } else {
        return "";
      }
    },
    downloadExl(row, type) {
      let lang = this.lang === 'zh' ? 'CN' : 'ENG'
      const href = `${process.env.BASE_URL}receive/download/excel/${type}/${lang}/${row.uuid}`
      window.open(href, '_blank')
    },
    // 切换 page 
    handlePageChange(pageNo) {
      this.dataTable.pageNo = pageNo 
      this.getHistoryList()
    },
    // 切换时间
    changeTime(value) {
      this.dataTable.timeValue = value
      this.getHistoryList()
    },
    // 获取表格信息
    async getHistoryList() {
      this.dataTable.isLoading = true;
      const res = await fetchHistoryList({
        type: this.allListNum,
        pageNo: this.dataTable.pageNo,
        pageSize: this.dataTable.pageSize,
        time: this.dataTable.timeValue
      });
      // console.log(res.data.historyData, 'res');
      this.dataTable.data = [];
      if(res.data.historyData.length) {
        this.dataTable.total = res.data.count
        res.data.historyData.forEach((item) => {
          // console.log(item.typeString)
          let c = {}
          try {
            const resultData = item.result_data && JSON.parse(item.result_data)
            // console.log(resultData);
            // 解析图形数据
            if(item.typeString === 'aff') {
              c = this.parameter.reduce((prev, curr) => {
                prev = {
                  ...prev,
                  ...this.setData(resultData[curr.key] && resultData[curr.key][0], curr.value),
                }
                return prev
              }, {})
              // 蛋白模块 - 图片
            } else if(item.typeString === 'pisa') {
              console.log(resultData)
              c = {
                img: (resultData && resultData.img) || ''
              }
            } else if(item.typeString === 'histogram') {
              this.parameter.forEach(curr => {
                c = resultData[curr.key] ||  {}
              })
            }
          } catch(e) {
            c = {}
          }


          this.dataTable.data.push({
            ...item,
            // 添加编辑功能
            isEdit: false,
            editValue: '',
            uploadTime: this.formatterTime(item.uploadTime),
            parme: (item.parme && JSON.parse(item.parme)) || {},
            result_data: c,
            typeString: item.typeString,
          } || {});
          this.dataTable.isLoading = false;
        });
      // console.log(this.dataTable.data, '列表');
      } else {
        this.dataTable.data = []
        this.dataTable.isLoading = false;
      }
    },

    // 处理数据格式
    setData(data, name = '') {
      if(data && !data.time) {
        throw new Error(`缺少 time 字段`)
      }
      const o = {}
      for (const k in data) {
        if(k === 'time') continue
        o[`${name}${k}`] = data.time.map((item, index) => [item, data[k][index]])
      }
      return o
    },
    goDetail(data) {
      this.$router.push({
        path: this.jumpUrl,
        query: { 
          name: data.fileName, 
          id: data.id, 
          time: data.uploadTime,
        },
      });
    },
  },
  computed: {
    TIMEOPTION() {
      return timeOption
    }
  }
};
</script>

<style lang="scss" scoped>
.table {
  padding: 20px;
  .toolbar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .time_selection {
      span {
        margin-right: 20px;
        cursor: pointer;
        font-weight: 700;
        color: #606266;
        font-size: 17px;
      }
      .active {
        color: #409EFF;
      }
    }
  }
}
</style>